package com.goldenautumn.prefabricate.activity.account

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.view.animation.AnimationUtils
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LanguageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.VibrateUtils
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.business.user.LoginUiState
import com.goldenautumn.prefabricate.business.user.UserViewModel
import com.goldenautumn.prefabricate.databinding.ActivityPhoneLoginBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.goldenautumn.prefabricate.widget.dialog.CountrySelectDialog
import com.gyf.immersionbar.ImmersionBar
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.isVisible
import qncx.external.common.compat.visibleOrInvisible
import qncx.external.common.utils.TUIRouter
import qncx.external.common.utils.ticker
import qncx.external.common.widget.colortext.ITextListener
import qncx.external.common.widget.colortext.SpannableText
import qncx.external.common.widget.view.TipsDialog
import java.util.concurrent.TimeUnit

class PhoneLoginActivity : BaseActivity<ActivityPhoneLoginBinding>(),ITextListener {

    private val mUserModel by viewModels<UserViewModel>()

    private var time = 0

    override fun getLayoutId(): Int  = R.layout.activity_phone_login

    override suspend fun main() {
        initImmersionBar()
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        mBinding.toolbar.setNavigationOnClickListener { onBackPressedDispatcher.onBackPressed() }

        var language = if(LanguageUtils.isAppliedLanguage()) LanguageUtils.getAppliedLanguage() else LanguageUtils.getSystemLanguage()
        mBinding.linearLayout2.visibleOrInvisible(language.language == "zh")
        mBinding.wechatBtn.visibleOrInvisible(language.language == "zh")

        var arr = resources.getStringArray(R.array.user_agreement)
        var spannableText =  SpannableText(mBinding.ruleTv.context,this)
        spannableText.setParam(getString(R.string.check_agreements),arr[0],arr[1], arr[0], arr[1])
        spannableText.setTargetStyle(qncx.external.common.R.color.colorPrimary, false)
        spannableText.setTextView(mBinding.ruleTv)

        mBinding.phone.doAfterTextChanged {
            var phone = mBinding.phone.text.toString()
            var code = mBinding.code.text.toString()
            mBinding.loginBtn.isEnabled = phone.length == 11 && code.length >= 4 && mBinding.protocol.isChecked
        }
        mBinding.code.doAfterTextChanged {
            var phone = mBinding.phone.text.toString()
            var code = mBinding.code.text.toString()
            mBinding.loginBtn.isEnabled = phone.length == 11 && code.length >= 4 && mBinding.protocol.isChecked
        }
        mBinding.protocol.setOnCheckedChangeListener { _, isChecked ->
            var phone = mBinding.phone.text.toString()
            var code = mBinding.code.text.toString()
            mBinding.loginBtn.isEnabled = phone.length == 11 && code.length >= 4 && isChecked
        }
        mBinding.country.setOnClickListener {
            CountrySelectDialog(1){

            }.onShow(supportFragmentManager.beginTransaction())
        }

        mBinding.loginBtn.isEnabled = false
        mBinding.loginBtn.setOnClickListener {
            var phone = mBinding.phone.text.toString()
            var code = mBinding.code.text.toString()
            mUserModel.onPhoneLogin(phone,code)
        }
        mBinding.sendBtn.setOnClickListener {
            var phone = mBinding.phone.text.toString()
            if(phone.length == 11 ){
                time = 60
                mUserModel.getCode(phone)
            } else {
                VibrateUtils.vibrate(50)
                mBinding.phone.startAnimation(AnimationUtils.loadAnimation(it.context, R.anim.shake_anim))

            }
        }

        mBinding.wechatBtn.setOnClickListener {
            if(mBinding.protocol.isChecked) {
                var intent = Intent(ConstantsAPI.ACTION_REFRESH_WXAPP)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    registerReceiver(object : BroadcastReceiver() {
                        override fun onReceive(context: Context?, intent: Intent?) {
                            var api = WXAPIFactory.createWXAPI(this@PhoneLoginActivity, getString(R.string.wechatId), true)
                            api.registerApp(getString(R.string.wechatId))
                            var req: SendAuth.Req = SendAuth.Req()
                            req.scope = "snsapi_userinfo"
                            req.state = "wechat_sdk_photo"
                            var isSend = api.sendReq(req)
                            LogUtils.d("发送微信登录请求${isSend}")
                        }
                    }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP), RECEIVER_EXPORTED)
                } else {
                    registerReceiver(object : BroadcastReceiver() {
                        override fun onReceive(context: Context?, intent: Intent?) {
                            var api = WXAPIFactory.createWXAPI(this@PhoneLoginActivity, getString(R.string.wechatId), true)
                            api.registerApp(getString(R.string.wechatId))
                            var req: SendAuth.Req = SendAuth.Req()
                            req.scope = "snsapi_userinfo"
                            req.state = "wechat_sdk_photo"
                            var isSend = api.sendReq(req)
                            LogUtils.d("发送微信登录请求${isSend}")
                        }
                    }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
                }
                sendBroadcast(intent)
            } else {
                VibrateUtils.vibrate(50)
                mBinding.protocolBtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_anim))
            }
        }

        var ticker = ticker(TimeUnit.SECONDS.toMillis(1))

        while (isActive) {
            select {
                mUserModel.loginRequests.onReceive {
                    when(it) {
                        is LoginUiState.LoginSuccess -> {
                            mBinding.loginBtn.showSucceed(1500)
                            mBinding.loginBtn.postDelayed({
                                ActivityUtils.finishActivity(PhoneLoginActivity::class.java)
                                finish()
                            },50)
                        }
                        is LoginUiState.LoginFail -> {
                            SPUtils.getInstance().put(Constants.IS_LOGIN,true)
                            SPUtils.getInstance().put(Constants.LOGIN_TOKEN,"e5cf5a19135133184afe117725a3489b")
                            onCenterToast("${it.msg}")
                            mBinding.loginBtn.showError(1500)
                        }
                        is LoginUiState.CodeResult -> {
                            if(it.msg == null) onCenterToast(getString(R.string.login_send_sms_msg))
                            else {
                                time = 0
                                onCenterToast("${it.msg}")
                            }
                        }
                    }
                }
                ticker.onReceive {
                    if(time == 0){
                        mBinding.sendBtn.isEnabled = true
                        mBinding.sendBtn.setText(R.string.get_verification)
                        mBinding.sendBtn.setTextColor(ContextCompat.getColor(this@PhoneLoginActivity,R.color.colorPrimary))
                    } else {
                        --time
                        mBinding.sendBtn.isEnabled = false
                        mBinding.sendBtn.text = String.format(getString(R.string.get_verification_second),"$time")
                        mBinding.sendBtn.setTextColor(ContextCompat.getColor(this@PhoneLoginActivity,R.color.colorPrimary77))
                    }
                }
            }
        }
    }

    override fun onClickText(url: String) {
        var bundle = Bundle()
        bundle.putString("START_ACTIVITY_PARAMS",url)
        TUIRouter.startActivityForResult(ActivityUtils.getTopActivity() as FragmentActivity,"ProtocolActivity",bundle,null)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}